import { mapState, mapMutations } from 'vuex'
export default {
	name: 'chatRoom',
	data() {
		return {
			ws:null,
			userId:null,
			message:"",
			messageList:[],
		}
	},
	computed: {
		...mapState([
			'token'
		]),
	},
	methods: {
		...mapMutations([
			'TOKEN'
		]),		
		submit(){
			if(this.message=='') return;
			this.ws.send(JSON.stringify({
				userId:this.userId,
				message:this.message
			}))
			this.message = "";
		},
		connectWS(){
			var that = this;
			//this.ws = new WebSocket("ws://192.168.1.111:1314");
			this.ws = new WebSocket("ws://60.205.218.105:1314");
			//this.ws = new WebSocket("ws://localhost:1314");
			this.ws.onopen = function(e){
				console.log('链接webSocket成功')
			}
			this.ws.onmessage = function(e){				
				var message = JSON.parse(e.data);
				
				if(message.type=='assign'){					
					that.userId = message.userId;
				}
				if(message.type=='welcome'){
					that.messageList.push({
						type:1,
						message:`欢迎游客${message.userId}加入聊天室`
					})
				}
				if(message.type=='leave'){
					that.messageList.push({
						type:1,
						message:`恭送游客${message.userId}离开聊天室`
					})
				}
				if(message.type=='message'){	
					var type = (message.userId == that.userId)?2:3;
					that.messageList.push({
						type:type,
						userId:message.userId,
						message:message.message
					})
				}
			}
			this.ws.onclose = function(e){
				console.log('链接关闭')
			}
		},
	},
	components: {

	},
	created() {
		document.title = "聊天室";
		this.connectWS();
		var that = this;
		document.onkeydown = function(e){
			if(e.keyCode == 13){
				that.submit();
			}
		}
	}
}